<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require_once(dirname(__FILE__) . "/Logger.php");

class EasyMysql {

    private $host;
    private $port;
    private $username;
    private $password;
    private $dbname;
    private $charset;
    private $conn;
    private $errno;
    private $error;

    function __construct($host, $port, $user, $passwd, $db, $charset) {
        $this->host = $host;
        $this->port = $port;
        $this->username = $user;
        $this->password = $passwd;
        $this->dbname = $db;
        $this->charset = $charset;

        $this->conn = $this->connect();
    }

    function __destruct() {
        if ($this->conn) {
            $this->conn->close();
        }
    }

    /**
     * EasyMysql::query()
     *
     * @param mixed $sql
     * @return
     *
     */
    public function query($sql) {
        $ret = array();
        $i = 0;
        $j = 0;
        if ($this->conn->multi_query($sql)) {
            do {
                if ($result = $this->conn->store_result()) {
                    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                        $ret [$j] [$i++] = $row;
                    }
                    $result->close();
                    $j++;
                }
            } while ($this->conn->more_results() && $this->conn->next_result());
        } else {
            throw new Exception("EasyMysql query error : " . mysqli_error($this->conn));
        }
        return $ret;
    }

    private function connect() {
        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
        if (!$this->conn) {
            $this->save_error();
            return NULL;
        }

        if (isset($this->charset)) {
            $this->conn->query("set names $this->charset");
        }

        return $this->conn;
    }

    /**
     * EasyMysql::save_error()
     *
     * @param mixed $dblink
     * @return
     *
     */
    private function save_error() {
        $this->errno = mysql_errno();
        $this->error = mysql_error();
    }

    public function error() {
        return $this->error;
    }

    public function errno() {
        return $this->errno;
    }

}
